#include "wav-file.h"
#include <string.h>
#include <stdio.h>

WavFile::WavFile(const string &filename)
    : filename(filename)
{
	strncpy(header.riff_tag, "RIFF", 4);
	strncpy(header.wave_tag, "WAVE", 4);
	strncpy(header.fmt_tag, "fmt ", 4);
	strncpy(header.data_tag, "data ", 4);
}

void WavFile::setParams(int sampleRate, int channels, int sampleBits)
{
	header.fmt_length   = 16;
	header.audio_format = 1;
	header.num_channels = channels;
	//采样率
	header.sample_rate = sampleRate;
	//采样率*通道*位数/8
	header.byte_rate   = sampleRate * channels * sampleBits / 8;
	header.block_align = sampleBits * channels / 8;
	//采样多少位
	header.bits_per_sample = sampleBits;
}

bool WavFile::writeData(uint8_t *data, uint32_t size)
{
	FILE *fp = fopen(filename.c_str(), "w");
	if(!fp)
	{
		fprintf(stderr, "Fail to fopen %s : %s \n", filename.c_str(), strerror(errno));
		return false;
	}

	header.riff_length = sizeof(wavfile_header_t) - 8 + size;
	header.data_length = size;
	//write wav heaer 写wav头
	int ret = fwrite(&header, sizeof(uint8_t), sizeof(header), fp);
	if(ret != sizeof(header))
	{
		fprintf(stderr, "Fail to fwrite %s   \n", strerror(errno));
	}
	//write pcm data 写wav数据
	ret = fwrite(data, sizeof(uint8_t), size, fp);
	if(ret != sizeof(header))
	{
		fprintf(stderr, "Fail to fwrite Data %s   \n", strerror(errno));
	}

	fclose(fp);

	return true;
}
